<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="box">
      <h2>compile</h2>
      <p>{{ name }}</p>
      <p>{{ age }}</p>
    </div>

    <script>
      const inner = document.querySelector("#box").innerHTML;

      const data = {
        name: "zhangsan",
        age: 20,
      };

      const compile = (node) => {
        // node.children用来获取到这个元素的所有的子节点
        // Array.from()或者扩展运算符，可以将类数组转成数组
        const children = [...node.children];
        // 双大括号的正则
        const reg = /\{\{(.*)\}\}/;

        children.forEach((item) => {
          // 去查看每个节点的内容是否有双大括号，如果有用data里面的变量去代替
          if (reg.test(item.textContent)) {
            item.innerHTML = data[RegExp.$1.trim()];
          }
        });
      };

      compile(document.querySelector("#box"));

      // observer数据监听器，对整个页面的所有数据进行监听
      const observer = (data, key, value) => {
        Object.defineProperty(data, key, {
          get() {
            return value;
          },
          set(val) {
            console.log(`${key}的值从${value}变成了${val}`);
            value = val;
            // console.log("页面需要更新了");
            document.querySelector("#box").innerHTML = inner;
            compile(document.querySelector("#box"));
          },
        });
      };

      Object.keys(data).forEach((item) => {
        observer(data, item, data[item]);
      });

      setTimeout(() => {
        data.name = "lisi";
      }, 3000);
    </script>
  </body>
</html>
